package my.xduscorequery;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class ScoreFetcher {
	private static String
		uid = null,
		psw = null,
		result=null;
	private static long timestamp=System.nanoTime();
	
	private final static String 
		BASE_OLD="http://125.76.215.232/xdjwWeb",
		BASE_NEW=BASE_OLD+"New",
		QUERY = "/studentStatus/queryScore/query_person_score.jsp",
		LOGIN = "/systemAdmin/Login.jsp?command=studentLogin",
		SUBMIT = "/Servlet/UsersControl"; 
	private static String VBASE;
	private static DefaultHttpClient httpclient = null;
	private static HttpResponse httpresponse = null;
	
	public static String fetchScore(String uid,String psw,boolean useProxy) throws ClientProtocolException, IOException, NoSuchAlgorithmException{
		httpclient=new DefaultHttpClient();
		if(uid.charAt(2)=='0')VBASE=BASE_OLD;
		else VBASE=BASE_NEW;
		String shareValue=null,secrete=null,tmp=null;
		if(uid == ScoreFetcher.uid && result!=null && System.nanoTime()-timestamp > 3600000000000l){
			return result;
		}
		ScoreFetcher.uid=uid;
		ScoreFetcher.psw=psw;
		HttpGet 
			login=new HttpGet(VBASE+LOGIN),
			query=new HttpGet(VBASE+QUERY);
		HttpPost
			submit=new HttpPost(VBASE+SUBMIT);
		/*proxy*/
		
		HttpHost proxy = new HttpHost("web-proxy.oa.com",8080);
		if(useProxy)httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		
		httpresponse = httpclient.execute(login);
		
		tmp=getResponseContent(httpresponse);
		login.abort();
		
		Matcher mc=
				Pattern
				.compile("sharedValue\\s+=\\s+(-?\\d+)")
				.matcher(tmp);
		if(mc.find())shareValue=mc.group(1);
		if(shareValue==null)return result;
		secrete = md5Hex(md5Hex(psw)+shareValue);
		
		//post data
		List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 
		nvps.add(new BasicNameValuePair("uid",uid));
		nvps.add(new BasicNameValuePair("password",secrete));
		nvps.add(new BasicNameValuePair("command","studentLogin"));
		submit.setEntity(new UrlEncodedFormEntity(nvps));
		httpclient.execute(submit);
		submit.abort();
		
		httpresponse = httpclient.execute(query);
		result=getResponseContent(httpresponse);
		query.abort();
		
		return  result;
	}
	
	
	static String getResponseContent(HttpResponse response) throws IllegalStateException, IOException{
		HttpEntity httpEntity= response.getEntity();
		StringBuffer ret=new StringBuffer("");
		System.out.println("1.Get Response Status: " + response.getStatusLine());
		
		if(httpEntity!=null){
			System.out.println("  Get ResponseContentEncoding():"+httpEntity.getContentEncoding());  
            System.out.println("  Content Length():"+httpEntity.getContentLength());  
            InputStream is = httpEntity.getContent();
            BufferedReader br=new BufferedReader(new InputStreamReader(is,"GBK"));
            String line;
			while((line=br.readLine())!=null)
			{
				ret.append(line).append("\n");
			}
			is.close();
		}
//		System.out.println(ret.toString());
		return ret.toString();
	}

	static String md5Hex(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{
		byte[] msg=str.getBytes("utf8");
		MessageDigest md=MessageDigest.getInstance("MD5");
		byte[] digest=md.digest(msg);
		StringBuffer hexString = new StringBuffer();
    	for (int i=0;i<digest.length;i++) {
    		String hex=Integer.toHexString(0xff & digest[i]);
   	     	if(hex.length()==1) hexString.append('0');
   	     	hexString.append(hex);
    	}
    	return hexString.toString();
	}
}
